package com.app.service;

import com.alibaba.fastjson.JSONObject;
import com.app.Timer.RecommendTimer;
import com.app.model.cache.RedisKeys;
import com.app.model.cache.UserInfoToCache;
import com.app.model.main.*;
import com.app.model.position.Position;
import com.app.model.position.PositionFlag;
import com.app.model.position.UserNearBy;
import com.app.model.response.*;
import com.app.model.response.v3.FansInfoResponseBody;
import com.app.model.response.v3.FocusInfoResponseBody;
import com.app.model.response.v3.OtherDetails;
import com.app.model.response.v3.UserDetails;
import com.app.model.solr.SolrFlag;
import com.app.model.util.ArticleFlag;
import com.app.model.util.CommonFlag;
import com.app.model.util.UserTitle;
import com.app.model.util.UserWithScore;
import com.app.repository.interfaces.*;
import com.app.service.imessage.IMService;
import com.app.service.imessage.ImessageService;
import com.app.support.utils.RedisUtil;
import com.app.support.utils.SHAUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.apache.solr.common.SolrDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.export.MetricExportProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.support.RestGatewaySupport;

import java.io.IOException;
import java.util.*;

/**
 * Created by Lichaojie on 2017/3/24. It's a beautiful day.
 */
@Service
public class UserService {

    private final Logger logger = Logger.getLogger(UserService.class);

    private final long TOKEN_EXPIRE = 60*60*24*30;

    @Autowired
    private LoginRecordMapper loginRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ResponseService responseService;
    @Autowired
    private SolrService solrService;
    @Autowired
    private SearchService searchService;
    @Autowired
    private RecommendTimer recommendTimer;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private PositionService positionService;
    @Autowired
    private IMService imService;
    @Autowired
    private FavoritesMapper favoritesMapper;
    @Autowired
    private ImessageService imessageService;
    @Autowired
    private FocusMapper focusMapper;


    //添加登录记录
    public boolean addLoginRecord(long userId){
        long now = System.currentTimeMillis();

        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setUserId(userId)
                .setLoginTime(Long.toString(now));

        //UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        //userInfo.setLastLoginTime(Long.toString(now));

        //if(loginRecordMapper.insert(loginRecord) == 1 && userInfoMapper.updateByPrimaryKeySelective(userInfo) == 1){
        if(loginRecordMapper.insert(loginRecord) == 1){
            return true;
        }else {
            return false;
        }
    }

    public RetStatus doRegister(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        String userName = (String)paraMap.get("userName");
        String password = (String)paraMap.get("password");

        User tuser = userMapper.selectByUserName(userName, (byte) 1);
        if(tuser != null){
            return responseService.doResponse(202);
        }

        User user = new User();
        user.setUserName(userName)
                .setPassword(password)
                .setType((byte) 1);

        //插入用户数据
        if(userMapper.insertSelective(user) == 1){

            Image image = imageMapper.selectByPrimaryKey(-1l);
            if(image == null){
                Image image1 = new Image();
                image1.setId(-1l);
                image1.setOrigin("");
                imageMapper.insertSelective(image1);
            }

            //插入用户信息数据
            User muser = userMapper.selectByUserName(userName, (byte) 1);
            UserInfo userInfo = new UserInfo();
            userInfo.setId(muser.getId())
                    .setRegisterTime(Long.toString(System.currentTimeMillis()));

            Favorites favorites = new Favorites();
            favorites.setUserId(muser.getId())
                    .setName("默认收藏夹")
                    .setFlag((byte) 1)
                    .setTime(Long.toString(System.currentTimeMillis()));

            if(userInfoMapper.insertSelective(userInfo) == 1 && favoritesMapper.insertSelective(favorites) == 1){
                return responseService.doResponse(100);
            }
        }

        return responseService.doResponse(200);
    }

    @Transactional
    public RetStatus doThirdRegister(String parameter){
        RetStatus retStatus = new RetStatus();
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        String uid = (String)paraMap.get("uid");
        String name = (String)paraMap.get("name");
        String gender = (String)paraMap.get("gender");
        String avator = (String)paraMap.get("avator");

        User rawUser = userMapper.selectByUID(uid,(byte)2);
        //第一次第三方登录，需要向数据库添加验证数据
        if(rawUser == null){
            //插入用户登录数据
            User user = new User();
            user.setUid(uid)
                    .setName(name)
                    .setType((byte) 2);
            User insertedUser = new User();
            if(userMapper.insertSelective(user) == 1){
                insertedUser = userMapper.selectByUID(uid,(byte)2);
            }

            //插入图片
            Image image = new Image();
            image.setOrigin(avator);
            Image insertedImage;
            insertedImage = imageMapper.selectByImage(avator);
            if(insertedImage == null && imageMapper.insertSelective(image) == 1){
                insertedImage = imageMapper.selectByImage(avator);
            }
//            if(imageMapper.insertSelective(image) == 1){
//                insertedImage = imageMapper.selectByImage(avator);
//            }

            //插入用户info
            UserInfo userInfo = new UserInfo();
            userInfo.setId(insertedUser.getId())
                    .setRegisterTime(System.currentTimeMillis() + "")
                    .setNickName(name)
                    .setGender(gender.equals("男") ? (byte) 1 : (byte) 0)
                    .setAvator(insertedImage.getId());

            Favorites favorites = new Favorites();
            favorites.setUserId(insertedUser.getId())
                    .setName("默认收藏夹")
                    .setFlag((byte) 1)
                    .setTime(Long.toString(System.currentTimeMillis()));

            if(insertedUser != null && insertedImage != null && userInfoMapper.insertSelective(userInfo) == 1
                    && favoritesMapper.insertSelective(favorites) == 1){

                //登录成功：生成token并加入缓存
                String key = "token" + insertedUser.getId();
                String token = SHAUtil.sha(key + insertedUser.getUid() + insertedUser.getName());
                if(!redisUtil.exists(key)){
                    redisUtil.set(key,token,TOKEN_EXPIRE);
                }else {
                    redisUtil.remove(key);
                    redisUtil.set(key,token,TOKEN_EXPIRE);
                }

                //将用户id和token返回给用户
                UserInfo tUserInfo = userInfoMapper.selectByPrimaryKey(insertedUser.getId());
                LoginResponseBody loginResponseBody = new LoginResponseBody();
                loginResponseBody.setUserId(insertedUser.getId())
                        .setToken(token)
                        .setAvator(imageMapper.selectByPrimaryKey(tUserInfo.getAvator()).getOrigin())
                        .setSchool(tUserInfo.getSchool())
                        .setNickName(tUserInfo.getNickName())
                        .setEducation(tUserInfo.getEducation())
                        .setGender(tUserInfo.getGender())
                        .setIntroduction(tUserInfo.getIntroduction())
                        .setLabel(tUserInfo.getLabel())
                        .setLocation(tUserInfo.getLocation())
                        .setSig(imessageService.computeSig(tUserInfo.getId()));

                //添加登录记录
                addLoginRecord(insertedUser.getId());

                retStatus.setCode(100)
                        .setMessage(RetCode.getMessage(100))
                        .setBody(loginResponseBody);

                return retStatus;
            }

        }else{
            String logStatus = RedisKeys.LOG_STATUS + rawUser.getId();
            if(redisUtil.exists(logStatus)){
                int status = redisUtil.get(logStatus);
                if(status == 1){
                    return responseService.doResponse(230);
                }
            }
            redisUtil.set(logStatus,1);

            //之后每次只需要将用户id和token值返回即可
            String key = "token" + rawUser.getId();
            String token = SHAUtil.sha(key + rawUser.getUid() + rawUser.getName());
            if(!redisUtil.exists(key)){
                redisUtil.set(key, token, (long) 60 * 60 * 24 * 30);
            }

            //添加登录记录
            addLoginRecord(rawUser.getId());

            UserInfo tUserInfo = userInfoMapper.selectByPrimaryKey(rawUser.getId());
            LoginResponseBody loginResponseBody = new LoginResponseBody();
            loginResponseBody.setUserId(rawUser.getId())
                    .setToken(token)
                    .setAvator(imageMapper.selectByPrimaryKey(tUserInfo.getAvator()).getOrigin())
                    .setSchool(tUserInfo.getSchool())
                    .setNickName(tUserInfo.getNickName())
                    .setEducation(tUserInfo.getEducation())
                    .setGender(tUserInfo.getGender())
                    .setIntroduction(tUserInfo.getIntroduction())
                    .setLabel(tUserInfo.getLabel())
                    .setLocation(tUserInfo.getLocation())
                    .setSig(imessageService.computeSig(tUserInfo.getId()));
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(loginResponseBody);

            return retStatus;
        }

        return responseService.doResponse(200);
    }

    public RetStatus checkIdentity( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userId = (long)id;
        String token = (String)paraMap.get("token");

        //logger.info("checkIdentity:" + "userId -- " + userId + ",token1 -- " + token);

        if(!redisUtil.exists("token" + userId)){
            return responseService.doResponse(210);
        }else{
            if(!(redisUtil.get("token" + userId)).equals(token)){
                //logger.info("checkIdentity:" + "userId -- " + userId + ",token2 -- " + redisUtil.get("token" + userId));
                return responseService.doResponse(208);
            }else{
                //添加登录记录
                addLoginRecord(userId);
                //return responseService.doResponse(100);
                /*
                String logStatus = RedisKeys.LOG_STATUS + userId;
                if(redisUtil.exists(logStatus)){
                    int status = redisUtil.get(logStatus);
                    if(status == 1){
                        return responseService.doResponse(230);
                    }
                }
                redisUtil.set(logStatus, 1);
                */
                CheckIdentityResponseBody checkIdentityResponseBody = new CheckIdentityResponseBody();
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
                String sig = imessageService.computeSig(userId);
                checkIdentityResponseBody.setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                        .setEducation(userInfo.getEducation())
                        .setGender(userInfo.getGender())
                        .setIntroduction(userInfo.getEducation())
                        .setLabel(userInfo.getLabel())
                        .setLocation(userInfo.getLocation())
                        .setNickName(userInfo.getNickName())
                        .setSchool(userInfo.getSchool())
                        .setSig(sig);

                RetStatus retStatus = new RetStatus();
                retStatus.setCode(100)
                        .setMessage(RetCode.getMessage(100))
                        .setBody(checkIdentityResponseBody);

                return retStatus;
            }
        }
    }

    public RetStatus doLogin( String parameter){
        RetStatus retStatus = new RetStatus();
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        String userName = (String)paraMap.get("userName");
        String password = (String)paraMap.get("password");

        //logger.info("userName:" + userName + ",password:" + password);

        User user = userMapper.selectByUserName(userName, (byte) 1);

        if(user != null && user.getPassword().equals(password)){

            //logger.info("user:" + user.getUserName() + "," + user.getPassword());
            String logStatus = RedisKeys.LOG_STATUS + user.getId();
            if(redisUtil.exists(logStatus)){
                int status = redisUtil.get(logStatus);
                if(status == 1){
                    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    //为测试方便，取消用户名密码登录时的在线验证
                    //return responseService.doResponse(230);
                }
            }
            redisUtil.set(logStatus,1);

            //登录成功：生成token并加入缓存
            String key = "token" + user.getId();
            String token = SHAUtil.sha(key + userName + password);
            if(!redisUtil.exists(key)){
                redisUtil.set(key,token,TOKEN_EXPIRE);
            }else {
                redisUtil.remove(key);
                redisUtil.set(key,token,TOKEN_EXPIRE);
            }

            //添加登录记录
            addLoginRecord(user.getId());

            UserInfo tUserInfo = userInfoMapper.selectByPrimaryKey(user.getId());
            LoginResponseBody loginResponseBody = new LoginResponseBody();
            loginResponseBody.setUserId(user.getId())
                    .setToken(token)
                    .setAvator(imageMapper.selectByPrimaryKey(tUserInfo.getAvator()).getOrigin())
                    .setSchool(tUserInfo.getSchool())
                    .setNickName(tUserInfo.getNickName())
                    .setEducation(tUserInfo.getEducation())
                    .setGender(tUserInfo.getGender())
                    .setIntroduction(tUserInfo.getIntroduction())
                    .setLabel(tUserInfo.getLabel())
                    .setLocation(tUserInfo.getLocation())
                    .setSig(imessageService.computeSig(tUserInfo.getId()));
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(loginResponseBody);
            return retStatus;

        }else{
            return responseService.doResponse(206);
        }
    }

    public RetStatus checkUid(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        String uid = (String)paraMap.get("uid");

        User user = userMapper.selectByUID(uid, (byte) 2);

        if(user == null){
            return responseService.doResponse(100);
        }else {
            return responseService.doResponse(202);
        }
    }

    public RetStatus checkPhone( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        String userName = (String)paraMap.get("userName");

        User user = userMapper.selectByUserName(userName, (byte) 1);
        if(user == null){
            return responseService.doResponse(100);
        }else{
            return responseService.doResponse(202);
        }
    }

    public RetStatus completeUserInfo( String parameter ) throws Exception{
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userId = (long)id;
        String avator = (String)paraMap.get("avator");
        String label = (String)paraMap.get("label");
        String nickName = (String)paraMap.get("nickName");
        String school = (String)paraMap.get("school");
        String education = (String)paraMap.get("education");
        String location = (String)paraMap.get("location");
        String introduction = (String)paraMap.get("introduction");
        int gender = (Integer)paraMap.get("gender");

        UserInfo userInfo1 = userInfoMapper.selectByNickname(nickName);
        if(userInfo1 != null){
            if(userInfo1.getId() != userId){
                return responseService.doResponse(312);
            }
        }

        Image image = new Image();
        image.setOrigin(avator);
        Image insertedImage;
        insertedImage = imageMapper.selectByImage(avator);
        if(insertedImage == null && imageMapper.insertSelective(image) == 1){
            insertedImage = imageMapper.selectByImage(avator);
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId)
                .setAvator(insertedImage.getId())
                .setGender((byte)gender)
                .setNickName(nickName)
                .setSchool(school)
                .setEducation(education)
                .setLocation(location)
                .setIntroduction(introduction)
                .setLabel(label)
                .setRegisterTime(System.currentTimeMillis() + "");
        //判断完善还是修改
        UserInfo tUserInfo = userInfoMapper.selectByPrimaryKey(userId);
        if(tUserInfo == null){//完善
            if(userInfoMapper.insertSelective(userInfo) != 1){
                return responseService.doResponse(200);
            }else {
                imService.sendMessage(37l,userId);
            }
        }else{
            if(tUserInfo.getLabel().equals("")){
                imService.sendMessage(37l,tUserInfo.getId());
            }
            if(userInfoMapper.updateByPrimaryKeySelective(userInfo) != 1){//修改
                return responseService.doResponse(200);
            }
        }

        //将频繁读取的用户信息放入缓存
        String key = "userInfo" + userInfo.getId();
        UserInfoToCache value = new UserInfoToCache();
        value.setUserId(userInfo.getId())
                .setAvator(avator)
                .setNickName(userInfo.getNickName());
        if(redisUtil.exists(key)){
            redisUtil.remove(key);
        }
        redisUtil.set(key, value);

        //将最新的用户信息加入solr，此处先加入消息队列
        redisUtil.setList(RedisKeys.USERINFOTOSOLR, userInfo);

        //将最新的用户信息加入到IM服务端
        if(imService.setInfo(userInfo)){
            return responseService.doResponse(100);
        }else {
            return responseService.doResponse(322);
        }


    }

    public RetStatus resetPassword( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        String userName = (String)paraMap.get("userName");
        String password = (String)paraMap.get("password");

        User user = userMapper.selectByUserName(userName,(byte)1);
        user.setPassword(password);
        if(userMapper.updateByPrimaryKeySelective(user) == 1){
            return responseService.doResponse(100);
        }else {
            return responseService.doResponse(200);
        }
    }

    public RetStatus modifyPassword( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");
        String oldPassword = (String)paraMap.get("oldPassword");
        String newPassword = (String)paraMap.get("newPassword");
        String token = (String)paraMap.get("token");

        String key = "token" + userId;
        if(redisUtil.exists(key)){
            String rawToken = redisUtil.get(key);
            if(rawToken.equals(token)){
                User user = userMapper.selectByPrimaryKey((long)userId);
                if(user.getPassword().equals(oldPassword)){
                    user.setPassword(newPassword);
                    userMapper.updateByPrimaryKeySelective(user);

                    return responseService.doResponse(100);
                }
                return responseService.doResponse(212);
            }
            return responseService.doResponse(208);
        }
        return responseService.doResponse(200);
    }

    public RetStatus doSearch( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userIdI = (long)id;
        String keywords = (String)paraMap.get("keywords");
        String labelStr = (String)paraMap.get("label");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        //添加搜索记录
        if(page == 0){
            searchService.addSearchRecord(keywords,labelStr,Long.toString(System.currentTimeMillis()), CommonFlag.USER,userIdI);
        }

        List resultList = null;

        String queryString;
        if(labelStr.equals("") && keywords.equals("")){
            return responseService.doResponse(220);
        }else {
            String[] labels = labelStr.split(",");
            queryString = keywords;
            for(String str : labels){
                queryString += (" " + str);
            }
        }


        resultList = solrService.query(queryString, SolrFlag.USER,page,number);

        if(resultList.size() == 0 && page == 0){
            return responseService.doResponse(214);
        }else if(resultList.size() == 0 && page != 0){
            return responseService.doResponse(216);
        }else{
            List<SearchUserResponseBody> userList = new ArrayList<>();
            for (Object object : resultList){
                SolrDocument solrDocument = (SolrDocument)object;

                long userId = Long.parseLong((String)solrDocument.getFieldValue("id"));
                if(userIdI == userId) {
                    continue;
                }
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);

                SearchUserResponseBody userResponseBody = new SearchUserResponseBody();
                userResponseBody.setUserId(userId)
                        .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                        .setLabel(userInfo.getLabel())
                        .setNickName(userInfo.getNickName())
                        .setIntroduction(userInfo.getIntroduction());
                userList.add(userResponseBody);
            }
            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(userList);
            return retStatus;
        }
    }

    public RetStatus doSearchWithDistance(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userId = (long)id;
        String keywords = (String)paraMap.get("keywords");
        String labelStr = (String)paraMap.get("label");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        List<UserNearBy> resulList = new ArrayList<>();

        //第一次请求
        if(page == 0){
            //添加搜索记录
            searchService.addSearchRecord(keywords,labelStr,Long.toString(System.currentTimeMillis()), CommonFlag.USER,userId);

            List resultList = null;

            String queryString;
            if(labelStr.equals("") && keywords.equals("")){
                return responseService.doResponse(220);
            }else {
                String[] labels = labelStr.split(",");
                queryString = keywords;
                for(String str : labels){
                    queryString += (" " + str);
                }
            }

            //首先取出较大数据量的搜索结果
            resultList = solrService.query(queryString, SolrFlag.USER,0,10000);

            UserInfo userInfoI = userInfoMapper.selectByPrimaryKey(userId);
            String positionStr = userInfoI.getPosition();
            String[] strArray = positionStr.split(",");
            Position myPosition = new Position(Double.parseDouble(strArray[0]),Double.parseDouble(strArray[1]));

            List<UserNearBy> userNearByList = new ArrayList<>();
            for (Object object : resultList){
                SolrDocument solrDocument = (SolrDocument)object;
                long tUserId = Long.parseLong((String)solrDocument.getFieldValue("id"));
                if(userId == tUserId) continue;
                UserInfo tUserInfo = userInfoMapper.selectByPrimaryKey(tUserId);
                String[] tStrArray = tUserInfo.getPosition().split(",");
                Position tPosition = new Position(Double.parseDouble(tStrArray[0]),Double.parseDouble(tStrArray[1]));
                double distance = positionService.getDistance(myPosition,tPosition);
                if(distance - PositionFlag.MAX_DISTANCE < 0){//找到所有在附近的用户
                    UserNearBy userNearBy = new UserNearBy();
                    userNearBy.setUserId(tUserId)
                            .setDistance(distance)
                            .setAvator(imageMapper.selectByPrimaryKey(tUserInfo.getAvator()).getOrigin())
                            .setLabel(tUserInfo.getLabel())
                            .setNickName(tUserInfo.getNickName())
                            .setIntroduction(tUserInfo.getIntroduction());
                    userNearByList.add(userNearBy);
                }
            }

            Collections.sort(userNearByList);

            String key = RedisKeys.SEARCH_USER_NEARBY + Long.toString(userId);
            if(redisUtil.exists(key)){
                redisUtil.remove(key);
            }
            redisUtil.set(key,userNearByList);

            resulList.addAll(userNearByList);
        }else {
            String key = RedisKeys.SEARCH_USER_NEARBY + Long.toString(userId);
            resulList.addAll((List<UserNearBy>) redisUtil.get(key));
        }

        int number1 = page * number;
        int number2 = page * number + number ;
        int number3 = resulList.size();
        long start = number1 > number3 ? number3 : number1;
        long end = number2 > number3 ? number3 : number2;

        List<UserNearBy> result = new ArrayList<>();
        for (long i = start; i < end; i ++){
            result.add(resulList.get((int)i));
        }

        if(result.size() == 0 && page == 0){
            return responseService.doResponse(214);
        }else if(result.size() == 0 && page != 0){
            return responseService.doResponse(216);
        }else {
            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(resulList);

            return retStatus;
        }

    }

    public RetStatus getRecommendLoadMore( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

//        Map<String,List<Long>> userRecommendMap = redisUtil.get(RedisKeys.RECOMMEND_USER_MAP);
//        if(userRecommendMap == null){
//            recommendTimer.userRecommendTimer();
//            userRecommendMap = redisUtil.get(RedisKeys.RECOMMEND_USER_MAP);
//        }


        //从redis取得Map，虽然加入redis时key为long，取出后key变为String
        List<Long> idList = redisUtil.get(RedisKeys.RECOMMEND_USER_LIST + Long.toString(userId));
        if(idList == null){
            recommendTimer.computeUserRecommend(userId);
            idList = redisUtil.get(RedisKeys.RECOMMEND_USER_LIST + Long.toString(userId));
        }

        long start = page * number > idList.size() ? idList.size() : page * number ;
        long end = page * number + number > idList.size() ? idList.size() : page * number + number ;

        List<RecommendUserResponseBody> userResponseBodyList = new ArrayList<>();
        for (long i = start;i < end; i ++){
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(idList.get((int)i));

            RecommendUserResponseBody recommendUserResponseBody = new RecommendUserResponseBody();
            recommendUserResponseBody.setUserId(userInfo.getId())
                    .setNickName(userInfo.getNickName())
                    .setLabel(userInfo.getLabel())
                    .setIntroduction(userInfo.getIntroduction())
                    .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin());

            userResponseBodyList.add(recommendUserResponseBody);
        }

        if(userResponseBodyList.size() > 0){
            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(userResponseBodyList);
            return retStatus;
        }else{
            return responseService.doResponse(216);
        }
    }

    public RetStatus getRecommendUpdate(String parameter){

        final int MAX_RECOMMEND_USER_NUMBER = 1000;

        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");


        List<LoginRecord> latestUser;//七天内登录记录
        Set<Long> idSet = new HashSet<>();//七天内所有登录的用户ID

        long time2 = System.currentTimeMillis();
        long time1 = time2 - 7*24*60*60*1000;

        latestUser = loginRecordMapper.getIdListBetween(Long.toString(time1),Long.toString(time2));
        for (LoginRecord loginRecord : latestUser){
            idSet.add(loginRecord.getUserId());
        }


        UserInfo userInfo = userInfoMapper.selectByPrimaryKey((long)userId);
        String labelString = userInfo.getLabel();
        String[] labels = labelString.split(",");
        String keywords= "";
        for (String label : labels){
            keywords += (label + " ");
        }

        List resultList = solrService.query(keywords, SolrFlag.USER,0,2000);

        List<Long> list = new ArrayList<>();//与每个用户匹配度最高的2000个用户的ID
        for (Object object : resultList){
            SolrDocument solrDocument = (SolrDocument)object;
            list.add(Long.parseLong((String)solrDocument.getFieldValue("id")));
        }

        List<Long> tempList = new ArrayList<>();
        tempList.addAll(list);

        for (Long id : tempList){//将匹配度高的用户中最近一周没登录过的用户去除
            if(!idSet.contains(id)){
                list.remove(new Long(id));
            }
        }

        //如果剩余数目还大于MAX_RECOMMEND_USER_NUMBER，只取MAX_RECOMMEND_USER_NUMBER个用户
        long listSize = list.size();
        if(listSize > MAX_RECOMMEND_USER_NUMBER){
            for (int j = MAX_RECOMMEND_USER_NUMBER; j < listSize; j ++){
                list.remove(j);
            }
        }

        //去除用户本身
        list.remove(new Long(userId));

//        Map<String,List<Long>> userRecommendMap = redisUtil.get(RedisKeys.RECOMMEND_USER_MAP);
//        if(userRecommendMap == null){
//            recommendTimer.userRecommendTimer();
//            userRecommendMap = redisUtil.get(RedisKeys.RECOMMEND_USER_MAP);
//        }
//        List<Long> lastList = userRecommendMap.get(Long.toString(userId));
        List<Long> lastList = redisUtil.get(RedisKeys.RECOMMEND_USER_LIST + Long.toString(userId));
        if(lastList == null){
            recommendTimer.computeUserRecommend(userId);
            lastList = redisUtil.get(RedisKeys.RECOMMEND_USER_LIST + Long.toString(userId));
        }

        //去掉上一次计算的所有推荐用户
        list.remove(lastList);

        //去掉list中的历史刷新数据
        List<Long> list1 = new ArrayList<>();
        String k = RedisKeys.RECOMMEND_USER_UPDATE_HISTORY + Long.toString(userId);
        if(redisUtil.exists(k)){
            List<Long> idList = redisUtil.get(k);
            for (Long id : list){
                if(!idList.contains(id)){
                    list1.add(id);
                }
            }
        }

        List<Long> resultIdList = new ArrayList<>();
        if(list1.size() > number){
            resultIdList.addAll(list1.subList(0,number));
        }else if (list1.size() > 0){
            resultIdList.addAll(list1);
        }else {
            return responseService.doResponse(216);
        }

        List<RecommendUserResponseBody> userResponseBodyList = new ArrayList<>();
        for (long id : resultIdList){
            UserInfo info = userInfoMapper.selectByPrimaryKey(id);

            RecommendUserResponseBody recommendUserResponseBody = new RecommendUserResponseBody();
            recommendUserResponseBody.setUserId(info.getId())
                    .setLabel(info.getLabel())
                    .setNickName(info.getNickName())
                    .setAvator(imageMapper.selectByPrimaryKey(info.getAvator()).getOrigin())
                    .setIntroduction(info.getIntroduction());

            userResponseBodyList.add(recommendUserResponseBody);
        }

        RetStatus retStatus = new RetStatus();
        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(userResponseBodyList);

        //每次刷新更新缓存
        String key = RedisKeys.RECOMMEND_USER_UPDATE_HISTORY + Long.toString(userId);
        List<Long> idList = new ArrayList<>();
        if(redisUtil.exists(key)){
            idList = redisUtil.get(key);
            redisUtil.remove(key);
        }
        for (Long id : resultIdList){
            idList.add(id);
        }
        redisUtil.set(key,idList);

        return retStatus;
    }

    public RetStatus getRecommendWithDistanceLoadMore(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        UserInfo userInfoI = userInfoMapper.selectByPrimaryKey((long) userId);
        String[] strArray = userInfoI.getPosition().split(",");
        Position myPosition = new Position(Double.parseDouble(strArray[0]),Double.parseDouble(strArray[1]));

//        Map<String,List<Long>> userRecommendMap = redisUtil.get(RedisKeys.RECOMMEND_USER_MAP);
//        if(userRecommendMap == null){
//            recommendTimer.userRecommendTimer();
//            userRecommendMap = redisUtil.get(RedisKeys.RECOMMEND_USER_MAP);
//        }

        List<Long> idList = redisUtil.get(RedisKeys.RECOMMEND_USER_WITH_DISTANCE_LIST + Long.toString(userId));
        if(page == 0 || idList == null){
            List<UserWithScore> list = redisUtil.get(RedisKeys.RECOMMEND_USER_LIST + Long.toString(userId));
            List<Long> idlist = new ArrayList<>();
            for (UserWithScore userWithScore : list){
                idlist.add(userWithScore.getUserId());
            }
            recommendTimer.computeUserRecommendWithDistance(userId,idlist);
            idList = redisUtil.get(RedisKeys.RECOMMEND_USER_WITH_DISTANCE_LIST + Long.toString(userId));
        }

        long start = page * number > idList.size() ? idList.size() : page * number ;
        long end = page * number + number > idList.size() ? idList.size() : page * number + number ;

        List<RecommendUserResponseBody> userResponseBodyList = new ArrayList<>();
        for (long i = start;i < end; i ++){
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(idList.get((int)i));
            String[] tStrArray = userInfo.getPosition().split(",");
            Position tPosition = new Position(Double.parseDouble(tStrArray[0]),Double.parseDouble(tStrArray[1]));
            double distance = positionService.getDistance(myPosition, tPosition);

            RecommendUserResponseBody recommendUserResponseBody = new RecommendUserResponseBody();
            recommendUserResponseBody.setUserId(userInfo.getId())
                    .setNickName(userInfo.getNickName())
                    .setLabel(userInfo.getLabel())
                    .setIntroduction(userInfo.getIntroduction())
                    .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                    .setDistance(distance);

            userResponseBodyList.add(recommendUserResponseBody);
        }

        if(userResponseBodyList.size() > 0){
            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(userResponseBodyList);
            return retStatus;
        }else{
            return responseService.doResponse(216);
        }
    }

    public RetStatus getRecommendWithDistanceUpdate(String parameter){
        final int MAX_RECOMMEND_USER_NUMBER = 1000;

        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");


        List<LoginRecord> latestUser;//七天内登录记录
        Set<Long> idSet = new HashSet<>();//七天内所有登录的用户ID

        long time2 = System.currentTimeMillis();
        long time1 = time2 - 7*24*60*60*1000;

        latestUser = loginRecordMapper.getIdListBetween(Long.toString(time1),Long.toString(time2));
        for (LoginRecord loginRecord : latestUser){
            idSet.add(loginRecord.getUserId());
        }


        UserInfo userInfo = userInfoMapper.selectByPrimaryKey((long)userId);
        String labelString = userInfo.getLabel();
        String[] labels = labelString.split(",");
        String keywords= "";
        for (String label : labels){
            keywords += (label + " ");
        }

        List resultList = solrService.query(keywords, SolrFlag.USER,0,2000);

        List<Long> list = new ArrayList<>();//与每个用户匹配度最高的2000个用户的ID
        for (Object object : resultList){
            SolrDocument solrDocument = (SolrDocument)object;
            list.add(Long.parseLong((String)solrDocument.getFieldValue("id")));
        }

        List<Long> tempList = new ArrayList<>();
        tempList.addAll(list);

        for (Long id : tempList){//将匹配度高的用户中最近一周没登录过的用户去除
            if(!idSet.contains(id)){
                list.remove(id);
            }
        }

        //如果剩余数目还大于MAX_RECOMMEND_USER_NUMBER，只取MAX_RECOMMEND_USER_NUMBER个用户
        long listSize = list.size();
        if(listSize > MAX_RECOMMEND_USER_NUMBER){
            for (int j = MAX_RECOMMEND_USER_NUMBER; j < listSize; j ++){
                list.remove(j);
            }
        }

        //去除用户本身
        list.remove(new Long(userId));

        List<Long> lastList = redisUtil.get(RedisKeys.RECOMMEND_USER_LIST + Long.toString(userId));
        if(lastList == null){
            recommendTimer.computeUserRecommend(userId);
            lastList = redisUtil.get(RedisKeys.RECOMMEND_USER_LIST + Long.toString(userId));
        }

        //去掉上一次计算的所有推荐用户
        list.remove(lastList);
        ////此时list包含所有刷新得到的用户，不考虑距离

        UserInfo userInfoI = userInfoMapper.selectByPrimaryKey((long) userId);
        String[] strArray = userInfoI.getPosition().split(",");
        Position myPosition = new Position(Double.parseDouble(strArray[0]),Double.parseDouble(strArray[1]));
        List<UserNearBy> userNearByList = new ArrayList<>();
        for (Long id : list){
            UserInfo tUserInfo = userInfoMapper.selectByPrimaryKey(id);
            String pStr = tUserInfo.getPosition();
            if(pStr.equals("")){
                continue;
            }
            String[] tStrArray = pStr.split(",");
            Position tPosition = new Position(Double.parseDouble(tStrArray[0]),Double.parseDouble(tStrArray[1]));
            double distance = positionService.getDistance(myPosition, tPosition);
            if(distance - PositionFlag.MAX_DISTANCE < 0){//找到所有在附近的用户
                UserNearBy userNearBy = new UserNearBy();
                userNearBy.setUserId(id)
                        .setDistance(distance);
                userNearByList.add(userNearBy);
            }
        }
        Collections.sort(userNearByList);
        List<Long> rList = new ArrayList<>();
        for (UserNearBy userNearBy : userNearByList){
            rList.add(userNearBy.getUserId());
        }

        //去掉list中的历史刷新数据
        List<Long> list1 = new ArrayList<>();
        String k = RedisKeys.RECOMMEND_USER_WITH_DISTANCE_UPDATE_HISTORY + Long.toString(userId);
        if(redisUtil.exists(k)){
            List<Long> idList = redisUtil.get(k);
            for (Long id : rList){
                if(!idList.contains(id)){
                    list1.add(id);
                }
            }
        }

        List<Long> resultIdList = new ArrayList<>();
        if(list1.size() > number){
            resultIdList.addAll(list1.subList(0,number));
        }else if (list1.size() > 0){
            resultIdList.addAll(list1);
        }else {
            return responseService.doResponse(216);
        }

        Map<Long,Double> userWithDistanceMap = new HashMap<>();
        for (UserNearBy userNearBy : userNearByList){
            userWithDistanceMap.put(userNearBy.getUserId(),userNearBy.getDistance());
        }

        List<RecommendUserResponseBody> userResponseBodyList = new ArrayList<>();
        for (long id : resultIdList){
            UserInfo info = userInfoMapper.selectByPrimaryKey(id);

            UserInfo tUserInfo = userInfoMapper.selectByPrimaryKey(id);
            String[] tStrArray = tUserInfo.getPosition().split(",");
            Position tPosition = new Position(Double.parseDouble(tStrArray[0]),Double.parseDouble(tStrArray[1]));
            double distance = positionService.getDistance(myPosition, tPosition);

            RecommendUserResponseBody recommendUserResponseBody = new RecommendUserResponseBody();
            recommendUserResponseBody.setUserId(info.getId())
                    .setLabel(info.getLabel())
                    .setNickName(info.getNickName())
                    .setAvator(imageMapper.selectByPrimaryKey(info.getAvator()).getOrigin())
                    .setIntroduction(info.getIntroduction())
                    .setDistance(distance);

            userResponseBodyList.add(recommendUserResponseBody);
        }

        RetStatus retStatus = new RetStatus();
        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(userResponseBodyList);


        //每次刷新更新缓存
        String key = RedisKeys.RECOMMEND_USER_WITH_DISTANCE_UPDATE_HISTORY + Long.toString(userId);
        List<Long> idList = new ArrayList<>();
        if(redisUtil.exists(key)){
            idList = redisUtil.get(key);
            redisUtil.remove(key);
        }
        for (Long id : resultIdList){
            idList.add(id);
        }
        redisUtil.set(key, idList);

        return retStatus;
    }

    public RetStatus getUserInfo(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userId = id;

        UserInfoResponseBody userInfoResponseBody = new UserInfoResponseBody();

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        long sArticleNum = articleMapper.getArticleNumber(userId, ArticleFlag.SHARE);
        long hArticleNum = articleMapper.getArticleNumber(userId, ArticleFlag.HELP);

        if(userInfo == null){
            return responseService.doResponse(200);
        }else {
            userInfoResponseBody.setsArticleNum(sArticleNum)
                    .sethArticleNum(hArticleNum)
                    .setLabel(userInfo.getLabel())
                    .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                    .setEducation(userInfo.getEducation())
                    .setGender(userInfo.getGender())
                    .setIntroduction(userInfo.getIntroduction())
                    .setLocation(userInfo.getLocation())
                    .setNickName(userInfo.getNickName())
                    .setSchool(userInfo.getSchool());

            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(userInfoResponseBody);

            return retStatus;
        }

    }

    public RetStatus setPosition(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userId = (long)id;
        String positionString = (String)paraMap.get("position");

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        if(userInfo != null){
            userInfo.setPosition(positionString);
            if(userInfoMapper.updateByPrimaryKeySelective(userInfo) != 1){
                return responseService.doResponse(200);
            }
        }else {
            return responseService.doResponse(200);
        }

        return responseService.doResponse(100);
    }

    public RetStatus checkStatus(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userId = (long)id;

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        if(userInfo == null){
            return responseService.doResponse(200);
        }

        byte status = userInfo.getStatus();
        JSONObject jsonObject = new JSONObject();
        if(status == 1 || status == 2){
            jsonObject.put("flag",1);
        }else {
            jsonObject.put("flag",0);
        }

        RetStatus retStatus = new RetStatus();
        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(jsonObject);
        return retStatus;
    }

    public RetStatus getMyArticleNum(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int id = (int)paraMap.get("userId");
        long userId = (long)id;

        long sArticleNum = articleMapper.getArticleNumber(userId, ArticleFlag.SHARE);
        long hArticleNum = articleMapper.getArticleNumber(userId, ArticleFlag.HELP);

        Map<String,Long> map = new HashMap<>();
        map.put("hArticleNum",hArticleNum);
        map.put("sArticleNum",sArticleNum);

        RetStatus retStatus = new RetStatus();
        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(map);

        return retStatus;

    }

    public RetStatus logout(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");

        String key = RedisKeys.LOG_STATUS + userId;
        redisUtil.set(key, 0);

        return responseService.doResponse(100);
    }


    public RetStatus getUserDetails(long userId){
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        long sArticleNum = articleMapper.getArticleNumber(userId, ArticleFlag.SHARE);
        long hArticleNum = articleMapper.getArticleNumber(userId, ArticleFlag.HELP);
        long funs = focusMapper.getFansNumber(userId);
        long focus = focusMapper.getFocusNumber(userId);

        UserDetails userDetails = new UserDetails();

        if(userInfo == null){
            return responseService.doResponse(200);
        }else {
            userDetails.setCoin(userInfo.getCoin())
                    .setSolvedProblem(userInfo.getsolvedProblems())
                    .setUpgrade(UserTitle.getPercent(userInfo.getTitle()))
                    .setTitle(UserTitle.title(userInfo.getTitle()))
                    .setFans(funs)
                    .setFocus(focus)
                    .setsArticleNum(sArticleNum)
                    .sethArticleNum(hArticleNum)
                    .setLabel(userInfo.getLabel())
                    .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                    .setEducation(userInfo.getEducation())
                    .setGender(userInfo.getGender())
                    .setIntroduction(userInfo.getIntroduction())
                    .setLocation(userInfo.getLocation())
                    .setNickName(userInfo.getNickName())
                    .setSchool(userInfo.getSchool());

            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(userDetails);

            return retStatus;
        }
    }

    public RetStatus getOtherDetails(long myId,long otherId){
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(otherId);
        long sArticleNum = articleMapper.getArticleNumber(otherId, ArticleFlag.SHARE);
        long hArticleNum = articleMapper.getArticleNumber(otherId, ArticleFlag.HELP);
        long funs = focusMapper.getFansNumber(otherId);
        long focus = focusMapper.getFocusNumber(otherId);

        int f1 = focusMapper.getRelationBetween(myId,otherId);
        int f2 = focusMapper.getRelationBetween(otherId,myId);


        OtherDetails otherDetails = new OtherDetails();

        if(userInfo == null){
            return responseService.doResponse(200);
        }else {
            otherDetails.setStatus(f1 < f2 ? (byte) 1 : f1 > f2 ? (byte) 2 : f1 == 1 && f2 == 1 ? (byte)3 : (byte)4)
                    .setUpgrade(UserTitle.getPercent(userInfo.getTitle()))
                    .setSolvedProblem(userInfo.getsolvedProblems())
                    .setCoin(userInfo.getCoin())
                    .setTitle(UserTitle.title(userInfo.getTitle()))
                    .setFans(funs)
                    .setFocus(focus)
                    .setsArticleNum(sArticleNum)
                    .sethArticleNum(hArticleNum)
                    .setLabel(userInfo.getLabel())
                    .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                    .setEducation(userInfo.getEducation())
                    .setGender(userInfo.getGender())
                    .setIntroduction(userInfo.getIntroduction())
                    .setLocation(userInfo.getLocation())
                    .setNickName(userInfo.getNickName())
                    .setSchool(userInfo.getSchool());

            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(otherDetails);

            return retStatus;
        }
    }

    public RetStatus getFansList(long userId,long lastId,int number,byte type){
        List<Long> ids;
        if(lastId == 0){
            ids = focusMapper.getFansListDESC(userId,lastId,number);
        }else {
            if(type == 0){
                ids = focusMapper.getFansListDESC(userId,lastId,number);
            }else {
                ids = focusMapper.getFansListASC(userId,lastId,number);
            }
        }

        RetStatus retStatus = new RetStatus();

        List<FansInfoResponseBody> list = new ArrayList<>(number);

        int f1,f2;
        for (long id : ids){
            f1 = focusMapper.getRelationBetween(userId,id);
            f2 = focusMapper.getRelationBetween(id,userId);

            FansInfoResponseBody responseBody = new FansInfoResponseBody();
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(id);
            responseBody.setStatus(f1 < f2 ? (byte) 1 : f1 > f2 ? (byte) 2 : f1 == 1 && f2 == 1 ? (byte)3 : (byte)4)
                    .setUserId(userInfo.getId())
                    .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                    .setLabel(userInfo.getLabel())
                    .setNickName(userInfo.getNickName())
                    .setIntroduction(userInfo.getIntroduction());
            list.add(responseBody);
        }

        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(list);
        return retStatus;
    }


    public RetStatus getFocusList(long userId,long lastId,int number,byte type){
        List<Long> ids;
        if(lastId == 0){
            ids = focusMapper.getFocusListDESC(userId,lastId,number);
        }else {
            if(type == 0){
                ids = focusMapper.getFocusListDESC(userId,lastId,number);
            }else {
                ids = focusMapper.getFocusListASC(userId,lastId,number);
            }
        }

        RetStatus retStatus = new RetStatus();

        List<FocusInfoResponseBody> list = new ArrayList<>(number);

        int f1,f2;
        for (long id : ids){
            f1 = focusMapper.getRelationBetween(userId,id);
            f2 = focusMapper.getRelationBetween(id,userId);

            FocusInfoResponseBody responseBody = new FocusInfoResponseBody();
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(id);
            responseBody.setStatus(f1 < f2 ? (byte) 1 : f1 > f2 ? (byte) 2 : f1 == 1 && f2 == 1 ? (byte)3 : (byte)4)
                    .setUserId(userInfo.getId())
                    .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                    .setLabel(userInfo.getLabel())
                    .setNickName(userInfo.getNickName())
                    .setIntroduction(userInfo.getIntroduction());
            list.add(responseBody);
        }

        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(list);
        return retStatus;
    }

}
